﻿using System;
using RaptorEngine.Managers;
using RaptorEngine;
using OilRigSumoWrestlers.Scenes.Menu;
using RaptorEngine.Components;
using Microsoft.Xna.Framework;

namespace OilRigSumoWrestlers.Controllables.Controllers
{
    /// <summary>
    /// Controllable for local human players
    /// </summary>
    class HumanControllable : PlayerControllable
    {
        private LogicalPlayerIndex _player;

        public HumanControllable(Entity entity, LogicalPlayerIndex player)
            : base(entity)
        {
            _player = player;
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            ProcessInput(gameTime);
        }

        private void ProcessInput(GameTime gameTime)
        {
            if (GameEngine.Instance.Input.CommandActive(GameConstant.MENU + _player.ToString()))
            {
                GameEngine.Instance.Scene.StopCurrentScene();
                GameEngine.Instance.Scene.PushScene(new PauseMenu(_player));
                GameEngine.Instance.Audio.PauseMusic();
                GameEngine.Instance.Scene.StartCurrentScene();
                GameEngine.Instance.Scene.ShowCurrentScene();
            }

            if (movable == null)
            {
                if (Entity.HasComponent(ComponentType.Movable))
                    movable = (Movable)Entity.GetComponent(ComponentType.Movable);
                else
                    throw new Exception("The player needs a movable component");
            }
            //Use controller if it is plugged in
            if (GameEngine.Instance.Input.IsPlayerBound(_player) && GameEngine.Instance.Input.GamePadPluggedIn(_player))
            {
                Move(GameEngine.Instance.Input.GetSticksState(_player).Left, gameTime);
            }
            else
            {
                //Use keyboard
                float x = 0, y = 0;
                if (GameEngine.Instance.Input.CommandActive(GameConstant.LEFT + _player.ToString()))
                {
                    x = -1;
                }
                else if (GameEngine.Instance.Input.CommandActive(GameConstant.RIGHT + _player.ToString()))
                {
                    x = 1;
                }

                if (GameEngine.Instance.Input.CommandActive(GameConstant.UP + _player.ToString()))
                {
                    y = 1;
                }
                else if (GameEngine.Instance.Input.CommandActive(GameConstant.DOWN + _player.ToString()))
                {
                    y = -1;
                }

                Move(new Vector2(x, y), gameTime);
            }

            if (GameEngine.Instance.Input.CommandActive(GameConstant.PUSH + _player.ToString()))
            {
                Push(gameTime);
            }
        }
    }
}
